package com.mxc.gift.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.lww.springcloudapi.entity.*;
import com.mxc.gift.mapper.TabCodeMapper;
import com.mxc.gift.mapper.TabSaleplanGiftcodeMapper;
import com.mxc.gift.mapper.TabSaleplanGiftlogMapper;
import com.mxc.gift.mapper.TabSaleplanGiftstockMapper;
import com.mxc.gift.service.TabSaleplanGiftcodeService;
import org.apache.ibatis.transaction.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 销售礼品编码定义表 服务实现类
 * </p>
 *
 * @author SHEN
 * @since 2021-03-11
 */
@Service
public class TabSaleplanGiftcodeServiceImpl extends ServiceImpl<TabSaleplanGiftcodeMapper, TabSaleplanGiftcode> implements TabSaleplanGiftcodeService {

    @Autowired
    TabSaleplanGiftcodeMapper tabSaleplanGiftcodeMapper;

    @Autowired
    TabSaleplanGiftstockMapper tabSaleplanGiftstockMapper;

    @Autowired
    TabSaleplanGiftlogMapper tabSaleplanGiftlogMapper;

    @Autowired
    TabCodeMapper tabCodeMapper;
    //生成十位随机数
    private static final Object OBJECT = new Object();
    private static       long   bIndex = 0;

    /**
     * s随机数方法
     *
     * @param length
     * @return
     */
    public static String createSerialNo(int length) {
        double max = Math.pow(10, length);
        String curSerial;
        synchronized (OBJECT) {
            if (++bIndex >= max) {
                bIndex = 0;
            }
            curSerial = bIndex + "";
        }
        while (curSerial.length() < length) {
            curSerial = "0" + curSerial;
        }
        return curSerial;
    }

    /**
     * 礼品录入
     *
     * @param tabSaleplanGiftcode
     * @return
     */
    @Transactional
    public boolean insertGiftCode(TabSaleplanGiftcode tabSaleplanGiftcode, TabEmployee tabEmployee) {
        //随机数 10位
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String now = sdf.format(new Date());
        String pma = now + createSerialNo(4);
        //新增礼品信息
        TabSaleplanGiftstock tabSaleplanGiftstock = new TabSaleplanGiftstock();
        tabSaleplanGiftcode
                .setGiftcode(pma)
                .setAreaid("430100")
                .setSaleplanid("1")
                .setGifttype("1")
                .setOptrid(tabEmployee.getEname())
                .setAcptsiteid(tabEmployee.getAcptsiteid())
                .setOptrdate(new Date());
        //礼品录入
        int insert = tabSaleplanGiftcodeMapper.insert(tabSaleplanGiftcode);
        //新增礼品库存
        tabSaleplanGiftstock.setAcptsiteid(tabEmployee.getAcptsiteid())//归属点
                .setGiftcode(pma)//礼品编码
                .setAreaid(tabSaleplanGiftcode.getAreaid())//地区编码
                .setTotalnum(tabSaleplanGiftcode.getStocknum())//入库数量
                .setStocknum(tabSaleplanGiftcode.getStocknum())//库存数量
                .setObtainnum(0)//领取数量
                .setLastIn(tabSaleplanGiftcode.getStocknum());//最后一次入库数
        //新增礼品库存
        int insert1 = tabSaleplanGiftstockMapper.insert(tabSaleplanGiftstock);
        if (insert > 0 && insert1 > 0) {
            return true;
        }
        return false;
    }

    /**
     * 礼品修改
     *
     * @param tabSaleplanGiftcode
     * @return
     */
    @Transactional
    public boolean updGiftCode(TabSaleplanGiftcode tabSaleplanGiftcode, TabEmployee tabEmployee) {
        if (tabSaleplanGiftcode.getAcptsiteid().length() > 3) {
            //根据营业厅名称查询营业编码
            QueryWrapper<TabCode> tabCodeQueryWrapper = new QueryWrapper<>();
            tabCodeQueryWrapper.eq("codeName", tabSaleplanGiftcode.getAcptsiteid());
            TabCode tabCode = tabCodeMapper.selectOne(tabCodeQueryWrapper);
            tabSaleplanGiftcode.setAcptsiteid(tabCode.getCode()+"");
        }
        //查询营销礼品库存表 旧归属点
        QueryWrapper<TabSaleplanGiftstock> tabSaleplanGiftstockQueryWrapper = new QueryWrapper<>();
        tabSaleplanGiftstockQueryWrapper.eq("GIFTCODE", tabSaleplanGiftcode.getGiftcode());
        TabSaleplanGiftstock tabSaleplanGiftstock = tabSaleplanGiftstockMapper.selectOne(tabSaleplanGiftstockQueryWrapper);
        //进行修改
        UpdateWrapper<TabSaleplanGiftcode> tabSaleplanGiftcodeUpdateWrapper = new UpdateWrapper<>();
        tabSaleplanGiftcodeUpdateWrapper
                .set("PRIZELEVEL", tabSaleplanGiftcode.getPrizelevel())  //奖品等级（1-6）
                .set("BEGINTIME", tabSaleplanGiftcode.getBegintime())  //生效时间 1
                .set("ENDTIME", tabSaleplanGiftcode.getEndtime()) //失效时间
                .set("OPTRID", tabEmployee.getEname())  //操作员
                .set("ACPTSITEID", tabSaleplanGiftcode.getAcptsiteid())//受理点
                .set("OPTRDATE", new Date())  //
                .set("REMARKS", tabSaleplanGiftcode.getRemarks())
                .eq("GIFTCODE", tabSaleplanGiftcode.getGiftcode());
        int update = tabSaleplanGiftcodeMapper.update(null, tabSaleplanGiftcodeUpdateWrapper);
        //查询库存表归属点跟礼品编码是否同时存在一条数据中
        QueryWrapper<TabSaleplanGiftstock> tabsa = new QueryWrapper<>();
        tabsa.eq("GIFTCODE", tabSaleplanGiftcode.getGiftcode())
                .eq("ACPTSITEID", tabSaleplanGiftcode.getAcptsiteid());
        TabSaleplanGiftstock tabSaleplanGiftstock1 = tabSaleplanGiftstockMapper.selectOne(tabsa);
        if (tabSaleplanGiftstock1 == null) {
            //不存在就新增一条库存数据
            TabSaleplanGiftstock tabSaleplanGiftstock2 = new TabSaleplanGiftstock();
            tabSaleplanGiftstock2
                    .setAcptsiteid(tabSaleplanGiftcode.getAcptsiteid())//归属点
                    .setGiftcode(tabSaleplanGiftcode.getGiftcode())//礼品编码
                    .setTotalnum(tabSaleplanGiftstock.getStocknum())//入库数量
                    .setStocknum(tabSaleplanGiftstock.getStocknum())//库存数量
                    .setLastIn(tabSaleplanGiftstock.getStocknum())//tabSaleplanGiftstock.getStocknum()
                    .setAreaid("430100");//地区编码
            int insert = tabSaleplanGiftstockMapper.insert(tabSaleplanGiftstock2);
            //修改完给原来的库存数据删除
            QueryWrapper<TabSaleplanGiftstock> tasdad = new QueryWrapper<>();
            tasdad.eq("GIFTCODE", tabSaleplanGiftcode.getGiftcode()).eq("ACPTSITEID", tabEmployee.getAcptsiteid());
            int i = tabSaleplanGiftstockMapper.delete(tasdad);
            if (insert == 0) {
                return false;
            }
        }
//        else {
//            //存在的话给她做修改
//            UpdateWrapper<TabSaleplanGiftstock> tabSaleplanGiftstockUpdateWrapper = new UpdateWrapper<>();
//            tabSaleplanGiftstockUpdateWrapper
//                    .set("STOCKNUM", tabSaleplanGiftstock.getStocknum() + tabSaleplanGiftstock1.getStocknum())
//                    .set("TOTALNUM", tabSaleplanGiftstock.getStocknum())
//                    .set("LAST_IN", tabSaleplanGiftstock.getStocknum())
//                    .eq("GIFTCODE", tabSaleplanGiftcode.getGiftcode())
//                    .eq("ACPTSITEID", tabSaleplanGiftcode.getAcptsiteid());
//            int update1 = tabSaleplanGiftstockMapper.update(null, tabSaleplanGiftstockUpdateWrapper);
//            //修改完给原来的库存数据删除
//            if (update1 == 0) {
//                return false;
//            }
//        }
        //进行完修改再对营销礼品异动表进行新增
        TabSaleplanGiftlog log = new TabSaleplanGiftlog();
        log.setGiftcode(tabSaleplanGiftcode.getGiftcode())//礼品编码 no
                .setOrdertype("3")//操作类型
                .setCount(tabSaleplanGiftstock.getStocknum())//修改数据的数量 no
                .setAreaid("430100")//地区编码 no
                .setOldDept(tabSaleplanGiftstock.getAcptsiteid())//旧归属点 no
                .setNewDept(tabSaleplanGiftcode.getAcptsiteid())//新归属点 no
                .setOptrid(tabEmployee.getEname())//操作员 no
                .setAcptsiteid(tabEmployee.getAcptsiteid())//受理点 no
                .setOptrdate(new Date())//操作时间 no
                .setTransn(UUID.randomUUID().toString().replace("-", "").toUpperCase());//流水号
        int insert = tabSaleplanGiftlogMapper.insert(log);
        if (update > 0 || insert > 0) {
            return true;
        }
        return false;
    }

    /**
     * 礼品删除
     *
     * @param
     * @return
     */
    @Transactional
    public boolean delGiftCode(String giftcide) {
        //查询删除的的礼品是否被领取,领取的话就不能删除
        QueryWrapper<TabSaleplanGiftstock> tabSaleplanGiftstockQueryWrapper = new QueryWrapper<>();
        tabSaleplanGiftstockQueryWrapper.eq("GIFTCODE", giftcide);
        TabSaleplanGiftstock tabSaleplanGiftstock = tabSaleplanGiftstockMapper.selectOne(tabSaleplanGiftstockQueryWrapper);
        if (tabSaleplanGiftstock.getObtainnum() != 0) {
            return false;
        } else {
            //没有被领取就删除礼品信
            QueryWrapper<TabSaleplanGiftcode> tabSaleplanGiftcodeQueryWrapper = new QueryWrapper<>();
            tabSaleplanGiftcodeQueryWrapper.eq("GIFTCODE", giftcide);
            int i = tabSaleplanGiftcodeMapper.delete(tabSaleplanGiftcodeQueryWrapper);
            //删除礼品库存信息
            QueryWrapper<TabSaleplanGiftstock> tabSaleplanGiftstockQueryWrapper1 = new QueryWrapper<>();
            tabSaleplanGiftstockQueryWrapper1.eq("GIFTCODE", giftcide);
            int i1 = tabSaleplanGiftstockMapper.delete(tabSaleplanGiftstockQueryWrapper1);
        }
        return true;
    }

    /**
     * 分页连表查询
     *
     * @param pageNo
     * @param pageSize
     * @param giftname,礼品名称
     * @param prizelevel，礼品等级
     * @param acptsiteid，操作员的营业厅
     * @return
     */
    @Override
    public List<TabSaleplanGiftcode> queryByGiftcode(Integer pageNo, Integer pageSize, String giftname, String prizelevel, String acptsiteid) {
        PageHelper.startPage(pageNo, pageSize);
        List<TabSaleplanGiftcode> tabSaleplanGiftcodes = tabSaleplanGiftcodeMapper.queryByGiftcode(giftname, prizelevel, acptsiteid);
        return tabSaleplanGiftcodes;
    }
}
